package cn.fl.project.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.api.IPrjContApiService;
import cn.fl.project.api.IProjectQueryApiService;
import cn.fl.project.condition.PrjCstBscInfoQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjCstBscInfoConstant;
import cn.fl.project.dto.PrjCstBscInfoDTO;
import cn.fl.project.service.IPrjCstBscInfoService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.transform.PrjCstBscInfoVOTransform;
import cn.fl.project.vo.PrjCstBscInfoVO;
import cn.fl.project.vo.PrjCstNpBscInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import fl.constant.facade.framework.constant.UploadConstant;
import fl.customer.facade.customer.constant.CustomerConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tc.esign.facade.contract.dto.req.common.ApiCommonReq;
import tc.esign.facade.contract.dto.req.query.SelectContractMchrReqDTO;
import tc.esign.facade.contract.dto.req.query.SelectUserContractReqDTO;
import tc.esign.facade.contract.dto.req.update.ApiDeleteContractReqDTO;
import tc.esign.facade.contract.dto.resp.query.SelectUserContractRespDTO;
import tc.esign.facade.esign.api.IContractQueryApiService;
import tc.esign.facade.esign.api.IContractUpdateApiService;
import tc.esign.facade.esign.dto.FilSignDTO;
import tc.esign.facade.esign.dto.FilSignInfoDTO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 项目客户基础信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjCstBscInfoServiceImpl implements IPrjCstBscInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IPrjCstBscInfoService.class);
	
	/**
	 * TODO项目 API 暴露服务
	 */
   @Autowired
	private IProjectApiService projectApiService;

   @Autowired
	private IProjectQueryApiService projectQueryApiService;

	/**
	 * 合同服务
	 */
	@Autowired
	private IPrjContApiService prjContApiService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Resource
    private IContractQueryApiService contractQueryApiService;
	@Resource
    private IContractUpdateApiService contractUpdateApiService;
   
	@Override
	public PrjCstBscInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		
		PrjCstBscInfoDTO dto = projectQueryApiService.searchPrjCstBscInfoById(id,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
	    return PrjCstBscInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(PrjCstBscInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		return this.projectApiService.addPrjCstBscInfo(PrjCstBscInfoVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjCstBscInfoApiService.removeById(id);
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return projectApiService.removePrjCstBscInfoByIds(ids);
    }

	@Override
	public boolean modify(PrjCstBscInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjCstBscInfoApiService.modify(PrjCstBscInfoVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return this.projectApiService.modifyPrjCstBscInfo(PrjCstBscInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		page = this.projectApiService.searchPrjCstBscInfoListPage(page,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		page.setResultList(PrjCstBscInfoVOTransform.toVOList((List<PrjCstBscInfoDTO>)page.getResultList()));
		return page;
	}

	@Override
	public void addPrjCstBscInfoList(List<PrjCstBscInfoVO> list,Long prjId,String cstRlTyp) throws BaseException {
		this.projectApiService.addPrjCstBscInfoList(PrjCstBscInfoVOTransform.toDTOList(list),prjId,cstRlTyp);
		
	}

	@Override
	public List<PrjCstBscInfoVO> searchList(PrjCstBscInfoQueryCondition qc) throws BaseException {
		if(null==qc){
			BaseLogUtils.info(logger, "modify", "查询对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		return PrjCstBscInfoVOTransform.toVOList(this.projectApiService.searchPrjCstBscInfoList(qc, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
	}

	@Override
	public Pager searchGuarListPage(Pager page) throws BaseException {
		Pager pager = projectApiService.searchGuarListPage(page);
		if(CollectionUtils.isNotEmpty(pager.getResultList())){
			List<PrjCstBscInfoVO> list =PrjCstBscInfoVOTransform.toVOList((List<PrjCstBscInfoDTO>)pager.getResultList());
			if(CollectionUtils.isNotEmpty(list)){//set担保信息
				Map<String,String> guaraTypMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), PrjCstBscInfoConstant.GUARA_TYP_CD) ;//担保属性
				Map<String,String> cntTypMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(),PrjCstBscInfoConstant.CODE_CNT_TYP_CD) ;//签署方式
				for(PrjCstBscInfoVO p : list){
					if(StringUtils.isEmpty(p.getRlCd())){
						p.setRlCd("8");
						p.setRlCdNm("担保人");
					}
					if (StringUtils.isNotEmpty(p.getGuaraTypCd())){
						p.setGuaraTypCdNm(guaraTypMap.get(p.getGuaraTypCd()));
					}
					if (StringUtils.isNotEmpty(p.getCntTypCd())){
						p.setCntTypCdNm(cntTypMap.get(p.getCntTypCd()));
					}
					//查询担保合同
					SelectUserContractReqDTO selectUserContractReqDTO = new SelectUserContractReqDTO();
					selectUserContractReqDTO.setQueryDontView("1");//是否查询无需在线展示的数据 1是 0 否  默认否
					SelectContractMchrReqDTO mchrReqDTO = new SelectContractMchrReqDTO();
					mchrReqDTO.setMchr1(PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO));
					selectUserContractReqDTO.setMchrs(Lists.newArrayList(mchrReqDTO));
					selectUserContractReqDTO.setCertTypeCd("0");//证件类型 0身份证
					selectUserContractReqDTO.setBusinessId(p.getPrjId());//业务主键
					selectUserContractReqDTO.setCertNo(p.getCertNo());
					selectUserContractReqDTO.setUserNm(p.getCstNm());
					if (CustomerConstant.CST_TYP_CD_NP.equals(p.getCstTypCd())){
						//以下pid,bid为贷前业务专用
						BaseLogUtils.newLogger("searchGuarListPage查询担保人合同Begin:prjId=" + p.getPrjId()+",selectUserContractReqDTO="+JSON.toJSONString(selectUserContractReqDTO)).info();
						DataResultDTO dataResultDTO = contractQueryApiService.selectUserContract(
								ApiCommonReq.getInstance("LSAENHUINSPLM", "9d210874b7e84addb1f123734c2c84e0").body(selectUserContractReqDTO), null);
						BaseLogUtils.newLogger("searchGuarListPage查询担保人合同End:contResultDTO=" + JSON.toJSONString(dataResultDTO)).info();
						if (dataResultDTO.getSuccess() == 1) {
							List<SelectUserContractRespDTO> selectUserContractRespDTOList = (List<SelectUserContractRespDTO>) dataResultDTO.getData();
							if (CollectionUtils.isEmpty(selectUserContractRespDTOList)) {
								p.setConSignSts(0);
								p.setConSignStsNm("未签署");
								p.setIsPushCon(0);
							} else {
								for (SelectUserContractRespDTO userContractRespDTO : selectUserContractRespDTOList) {
									if (null!=userContractRespDTO.getSignSts() && 1==userContractRespDTO.getSignSts()) {
										p.setConSignSts(1);
										p.setConSignStsNm("已签署");
										p.setIsPushCon(1);
									} else {
										p.setConSignSts(0);
										p.setConSignStsNm("未签署");
										p.setIsPushCon(1);
									}
								}
							}
						}
					}else {
						p.setConSignSts(null);
						p.setConSignStsNm("");
						p.setIsPushCon(1);
					}
				}
			}
			pager.setResultList(list);
		}
		return pager;
	}

	@Override
	public boolean modifyPrjCstBscInfoList(List<PrjCstBscInfoVO> list) throws BaseException {
	 return	this.projectApiService.modifyPrjCstBscInfoList(PrjCstBscInfoVOTransform.toDTOList(list));
	}

	@Override
	public boolean removeCstAndDelCont(Long id, Long prjId, String guaraTypCd, String isPushCon) throws BaseException {
    	Boolean result = false;
    	String prjContCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO);
    	String cfgDtlCd = "";
		if (PrjCstBscInfoConstant.GUARA_TYP_CD_RELATE.equals(guaraTypCd)){
			cfgDtlCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO_LDZRBZHT_OL);
		}else {
			cfgDtlCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO_LDZRBZHT);
		}
		if ("1".equals(isPushCon)){
			BaseLogUtils.newLogger("开始删除已推送的连代担保合同：prjId="+prjId + "id="+id + ",cfgDtlCd=" + cfgDtlCd).info();
			if (this.delContByPrjCst(id, prjContCd, cfgDtlCd)){//若删除成功
				BaseLogUtils.newLogger("开始删除担保人信息id="+id + ",prjId=" + prjId).info();
				List<Long> idList = new ArrayList<Long>();
				idList.add(id);
				result = this.removeByIds(idList);
			}
		}else {
			BaseLogUtils.newLogger("开始删除担保人信息id="+id + ",prjId=" + prjId).info();
			List<Long> idList = new ArrayList<Long>();
			idList.add(id);
			result = this.removeByIds(idList);
		}
		return result;
	}

	@Override
	public boolean modifyCstAndDelCont(PrjCstBscInfoVO prjCstBscInfoVO) throws BaseException {
        Integer isPushCon = prjCstBscInfoVO.getIsPushCon();
    	Long prjId = prjCstBscInfoVO.getPrjId();
        BaseLogUtils.newLogger("modifyCstAndDelCont==Begin: isPush=prjId" + prjId + isPushCon).info();
    	Boolean result = false;
    	String prjContCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO);
    	String cfgDtlCd = "";
    	if (1==isPushCon) {//修改纸质合同
			if (PrjBscInfoConstant.CODE_PRJ_CNT_TYP_CD_PAPER.equals(prjCstBscInfoVO.getCntTypCd()) && null != prjId) {
				cfgDtlCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO_LDZRBZHT_OL);
			}
			BaseLogUtils.newLogger("开始删除修改为纸质的已推送的连代担保合同：prjId=" + prjId + ",id=" + prjCstBscInfoVO.getId() + ",cfgDtlCd=" + cfgDtlCd).info();
            this.delContByPrjCst(prjCstBscInfoVO.getId(), prjContCd, cfgDtlCd);
		}
    	if (3==isPushCon){//修改担保方式
            if(StringUtils.isNotEmpty(prjCstBscInfoVO.getGuaraTypCd()) && null != prjId) {
            	if (PrjCstBscInfoConstant.GUARA_TYP_CD_COMPENSATORY.equals(prjCstBscInfoVO.getGuaraTypCd())) {//若修改后担保属性为代偿，则删除原担保属性为连代的合同（线上签署版）
                    cfgDtlCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO_LDZRBZHT_OL);
                } else {
                    cfgDtlCd = PropertiesCacheUtils.getProperty(UploadConstant.CFG_PRJ_CONT_DANBAO_LDZRBZHT);
                }
			}
            BaseLogUtils.newLogger("开始删除修改担保属性且已推送的连代担保合同：prjId=" + prjId + ",id=" + prjCstBscInfoVO.getId() + ",cfgDtlCd=" + cfgDtlCd).info();
            this.delContByPrjCst(prjCstBscInfoVO.getId(), prjContCd, cfgDtlCd);
        }
        BaseLogUtils.newLogger("开始修改担保人信息prjId=" + prjId + ",prjCstBscInfoVO=" + JSON.toJSONString(prjCstBscInfoVO)).info();
    	List<PrjCstBscInfoVO> list = new ArrayList<PrjCstBscInfoVO>();
        list.add(prjCstBscInfoVO);
        result = this.modifyPrjCstBscInfoList(list);
		return result;
	}

	public Boolean delContByPrjCst(Long id, String prjContCd , String cfgDtlCd) throws BaseException {
    	Boolean result = false;
    	PrjCstBscInfoVO prjCstBscInfoVO = this.selectById(id);
		SelectUserContractReqDTO selectUserContractReqDTO = new SelectUserContractReqDTO();
		selectUserContractReqDTO.setQueryDontView("1");//是否查询无需在线展示的数据 1是 0 否  默认否
		selectUserContractReqDTO.setMchrs(Lists.newArrayList(new SelectContractMchrReqDTO(prjContCd,cfgDtlCd)));//合同主配置，子配置
		selectUserContractReqDTO.setCertTypeCd("0");//证件类型 0身份证
		selectUserContractReqDTO.setBusinessId(prjCstBscInfoVO.getPrjId());//业务主键
		selectUserContractReqDTO.setCertNo(prjCstBscInfoVO.getCertNo());
		selectUserContractReqDTO.setUserNm(prjCstBscInfoVO.getCstNm());
		//以下pid,bid为贷前业务专用
		BaseLogUtils.newLogger("delContByPrjCst查询担保人合同Begin:prjId=" + prjCstBscInfoVO.getPrjId()+",selectUserContractReqDTO="+JSON.toJSONString(selectUserContractReqDTO)).info();
		DataResultDTO dataResultDTO = contractQueryApiService.selectUserContract(
				ApiCommonReq.getInstance("LSAENHUINSPLM", "9d210874b7e84addb1f123734c2c84e0").body(selectUserContractReqDTO), null);
		BaseLogUtils.newLogger("delContByPrjCst查询担保人合同End:contResultDTO=" + JSON.toJSONString(dataResultDTO)).info();
		if (dataResultDTO.getSuccess() == 1) {
			List<SelectUserContractRespDTO> selectUserContractRespDTOList = (List<SelectUserContractRespDTO>) dataResultDTO.getData();
			if (CollectionUtils.isNotEmpty(selectUserContractRespDTOList)) {
				List<Long> delList = new ArrayList<>();
				for (SelectUserContractRespDTO selectUserContractRespDTO : selectUserContractRespDTOList) {
					Long contractId = selectUserContractRespDTO.getContractId();
					delList.add(contractId);
				}
				List<String> olContIdList = new ArrayList<>();
				for (Long filId : delList){
					olContIdList.add(String.valueOf(filId));
				}
				BaseLogUtils.newLogger("删除合同记录开始：delList=" + JSON.toJSONString(olContIdList)).info();
				boolean delContRec = this.prjContApiService.removeContRecByOlcontIds(olContIdList);
				BaseLogUtils.newLogger("删除合同记录完成：" + delContRec).info();
				ApiDeleteContractReqDTO apiDeleteContractReqDTO = new ApiDeleteContractReqDTO();
				apiDeleteContractReqDTO.setContractId(delList);
				BaseLogUtils.newLogger("searchGuarListPage删除担保人合同Begin:apiDeleteContractReqDTO=" + JSON.toJSONString(apiDeleteContractReqDTO)).info();
				DataResultDTO delResultDTO = contractUpdateApiService.deleteContract(
						ApiCommonReq.getInstance("SHSKEMFWD91KD", "744266c084634388acbad79157a76ea8").body(apiDeleteContractReqDTO));
				BaseLogUtils.newLogger("searchGuarListPage删除担保人合同End:delResultDTO",JSON.toJSONString(delResultDTO)).info();
				if(delResultDTO.getSuccess()==1){
					result = true;
				}
			}
		}
		return result;
	}
}
